import { reactive, ref } from 'vue'
import { ElMessage, dayjs, type FormRules } from 'element-plus'
import { AsyncRecursion, creatAsyncRecursion } from '@src/utils/asyncRecursion'
import { promisetTimeOut } from '@src/utils/common'

import type { GetAllNodeDataParams, RuleForm } from './type'
import { DataSourceTypeEnum } from "@src/globalData/enum";
import { dataTypeList, defaultNodeIdsData, getAllNodeData, getReplaceNodeIdsData, saveReplaceNodeIdsData, validateNodeIds, yunNaoSaveNodeData } from "./generate";
import { betweenStartEndDays, startAutoGetdata, stopAutoGetdata, validateTimeMinute } from '../../generate';

  /**
   * 【现货市场】-【现货交易】-【日前交易结果】-【一次日前节点电价查询】
   * 全网所有节点日前出清节点电价
   * D + 1
   * AHEAD_NODE_PRICE_INFO = "ahead_node_price_info"
   */
  /**
   * https://pmos.sd.sgcc.com.cn:18080/trade/main/home/changeDate.do?pdate=2024-03-19&_=1711692352927
   * 【现货市场】-【现货交易】-【实时交易结果】-【实时节点电价查询】
   * 全网所有节点实时出清节点电价-临时
   * D - 1
   * ACT_NODE_PRICE_INFO = "act_node_price_info",
   */

export const useBatchData = (ruleFormRef:any, replaceFormRef:any) => {
  const loading = ref(false)

 /** isHandle 1. false: 获取120个节点的数据，在getOneNodeData中自动替换; 2. true: 只获取替换节点的数据，在getOneNodeData中自动替换 */
 const isHandle = ref(false)


  const reqHistory = ref<{ certainDate: string, reqTypes: string }[]>([])

  const replaceForm = reactive({
    nodeIds: JSON.stringify(defaultNodeIdsData)
  })

  const ruleForm = reactive<RuleForm>({
    certainDate: [dayjs().subtract(0, 'day').format('YYYY-MM-DD'), dayjs().subtract(0, 'day').format('YYYY-MM-DD')],
    reqType: DataSourceTypeEnum.AHEAD_NODE_PRICE_INFO,
    uniqueCode:''
  })

  const init = async () => {
    const nodeIds = await getReplaceNodeIdsData()
    replaceForm.nodeIds = JSON.stringify(nodeIds)
  }

  /** 重置 */
  const replaceReset = () => {
    replaceForm.nodeIds = JSON.stringify(defaultNodeIdsData)
    replaceSave()
  }
  /** 保存 */
  const replaceSave = async () => {
    if (!replaceFormRef?.value) return
    await replaceFormRef.value.validate()
    saveReplaceNodeIdsData(JSON.parse(replaceForm.nodeIds))
  }
  /** 取消 */
  const replaceCancel = async () => {
    const data = await getReplaceNodeIdsData()
    replaceForm.nodeIds = JSON.stringify(data)
  }
  const replaceRules = reactive({
    nodeIds: [{ validator: validateNodeIds, trigger: 'change' }],
  })

  let pickedStartDate:Date | null = null
  const calendarChange = (pickedDate:Date[]) => {
    const [min, max] = pickedDate
    if (max) {
      pickedStartDate = null
    } else {
      pickedStartDate = min
    }
  }

  /** 最多选择10天的时间 */
  const disabledDate = (date: Date) => {
   const appEnv = import.meta.env.VITE_APP_ENV
   if(/^dev/.test(appEnv)) return false
   
    const theTime = date.getTime()

    const maxDate = dayjs().subtract(0, 'day').valueOf()
    if (!pickedStartDate) {
      return theTime > maxDate
    }

    const minDate = dayjs(pickedStartDate).subtract(186, 'day').valueOf()

    return theTime < minDate || theTime > maxDate
  }

  const validateUniqueCode = (rule: any, value: any, callback: any) => {
    if (String(value).toLowerCase() !== 'hd2024') {
      callback(new Error('验证码输入错误'))
    } else {
      callback()
    }
  }

  const rules = reactive<FormRules<GetAllNodeDataParams>>({
    certainDate: [
      { required: true, message: '请选择数据日期', trigger: 'blur' },
    ],
    reqType: [
      {
        required: true,
        message: '请选择数据类型',
        trigger: 'blur',
      },
    ],
    uniqueCode: [
      {
        required: true,
        message: '请输入验证码',
        trigger: 'blur',
      },
      { validator: validateUniqueCode, trigger: 'blur' }
    ]
  })

  /** 显示请求成功的历史 */
  const setReqHistory = (certainDate:string) => {
    const {reqType} = ruleForm
    reqHistory.value.unshift({
      certainDate,
      reqTypes:  dataTypeList.find((item) => item.value === reqType)?.label || ''
    })
  }

  /** 请求一天的数据 */
  const reqOneCertainDateData = async (certainDate:string) => {
    try {
      const nodeData = await getAllNodeData({...ruleForm, certainDate}, undefined, isHandle.value)
      await yunNaoSaveNodeData(nodeData)
      setReqHistory(certainDate)
    }catch(e) {
      console.error(e)
      ElMessage.error('获取数据失败！ 请刷新主系统和子系统后重试')
    }
  }

  const reqData = async () => {
    stopAutoGetdata()
    try {
      loading.value = true
    
      await creatAsyncRecursion(AsyncRecursion, {
        stepAsyncFnParamsList: betweenStartEndDays(ruleForm.certainDate[0], ruleForm.certainDate[1]),
        stepAsyncFn: reqOneCertainDateData,
        stepCb: async () => await promisetTimeOut(1000), // 每天延时 1s
        stepAsyncNum: 1,
        errBreak: false
      }).start()

      ElMessage.warning('获取数据结束')
    }catch(e) {
      console.error(e)
      ElMessage.error('获取数据失败！ 请刷新主系统和子系统后重试')
    }finally {
      loading.value = false
      startAutoGetdata()
    }
  }

  const submitForm = async (handle = false) => {
    if (!ruleFormRef?.value) return
    if(!validateTimeMinute()) return
    await ruleFormRef.value.validate()
    isHandle.value = handle
    reqData()
  }

  const resetForm = () => {
    if (!ruleFormRef?.value) return
    ruleFormRef.value.resetFields()
  }

  return {
    init,
    loading,

    replaceForm,
    replaceRules,
    replaceSave,
    replaceCancel,
    replaceReset,

    ruleForm,
    rules,
    submitForm,
    resetForm,
    reqHistory,
    disabledDate,
    calendarChange
  }
}